package com.qiantu.phone.ui.activity;

import static com.qiantu.phone.ui.fragment.device.BaseDeviceFragment.STATUS;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.bar.TitleBar;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.view.ShapeEditText;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.IntTaskID;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.MusicListBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.adapter.MusicSearchAdapter;
import com.qiantu.phone.ui.fragment.MusicListFragment;
import com.qiantu.phone.ui.fragment.MusicTextFragment;
import com.qiantu.phone.utils.LinkageDataHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class PlayMusicSearchActivity  extends AppActivity {
    private ShapeEditText edit_search;
    private String serialNo;
    private String dialog_sign;
    private String musicID = "none_sign";
    private TitleBar titlebar;
    private int checkCount = 0;
    private long taskID;

    private RecyclerView recyclerView;

    MusicSearchAdapter musicSearchAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_play_music_search;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        serialNo = intent.getStringExtra("serialNo");
        dialog_sign = intent.getStringExtra("dialog_sign");
        titlebar = findViewById(R.id.titlebar);
        edit_search = findViewById(R.id.edit_search);
        recyclerView = findViewById(R.id.music_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        musicSearchAdapter = new MusicSearchAdapter(getContext());
        musicSearchAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                MusicListBean.MiguMusicDtos dtos = musicSearchAdapter.getItem(position);
                if (dialog_sign != null && dialog_sign.equals("deviceDialog")){
                    saveMusicData(dtos);
                }else {
                    SwitchMusicOperation(dtos.getMusicID());
                }
            }
        });
        recyclerView.setAdapter(musicSearchAdapter);

        initedit();
    }

    //搜索框监听
    private void initedit() {
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == EditorInfo.IME_ACTION_SEARCH)){
                    searchMusic();
                }
                return false;
            }
        });
    }

    private void searchMusic(){
        LLHttpManager.searchMusic(this,serialNo,edit_search.getText().toString(),new HttpCallback<HttpData<IntTaskID>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<IntTaskID> result) {
                super.onSucceed(result);
                taskID =  result.getData().getTaskId();
                checkCount = 0;
                postDelayed(pollingRunnable, 1000);//2秒后开始轮询
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private final Runnable pollingRunnable = new Runnable() {
        @Override
        public void run() {
            musicSearchQuery( );
        }
    };

    public void musicSearchQuery() {
        LLHttpManager.searchMusicQuery(this, serialNo, taskID, new HttpCallback<HttpData<MusicListBean>>(this) {
            @Override
            public void onSucceed(HttpData<MusicListBean> result) {
                super.onSucceed(result);
                List<MusicListBean.MiguMusicDtos> dtos = result.getData().getMiguMusicDtos();
                if(dtos.size() > 0){
                    musicSearchAdapter.setData(dtos);
                    if(getContext() != null && getContext() instanceof AppActivity) {
                        ((AppActivity) getContext()).hideDialog();
                    }
                }else{
                    if(checkCount < 3){
                        checkCount++;
                        postDelayed(pollingRunnable, 1000);//2秒后开始轮询
                    }else{
                        ToastUtils.show("搜索超时");
                        if(getContext() != null && getContext() instanceof AppActivity) {
                            ((AppActivity) getContext()).hideDialog();
                        }
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                if(checkCount < 3){
                    checkCount++;
                    postDelayed(pollingRunnable, 1000);//2秒后开始轮询
                }else{
                    ToastUtils.show("搜索超时");
                    if(getContext() != null && getContext() instanceof AppActivity) {
                        ((AppActivity) getContext()).hideDialog();
                    }
                }
            }
        });
    }

    private void SwitchMusicOperation(String musicID) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> statusMap=new HashMap<>();
        map.put("songid",musicID);
        statusMap.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),serialNo,statusMap,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                finish();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    public void saveMusicData(MusicListBean.MiguMusicDtos dtos){
        Intent intent = new Intent();
        intent.putExtra("musicid",dtos.getMusicID());
        intent.putExtra("musicName",dtos.getMusicName());
        intent.putExtra("picUrl",dtos.getPicURL());
        intent.putExtra("signerName",dtos.getSingerName());
        setResult(Activity.RESULT_OK,intent);
        finish();
    }

    @Override
    protected void initData() {
    }
}
